package g2.routemaster.gui.actions;

import g2.routemaster.gui.ApplicationStart;
import g2.routemaster.gui.GManager;
import g2.routemaster.gui.wizards.AddPlayerWizard;
import g2.routemaster.model.GameManager;
import g2.routemaster.model.SeatPlace;

import java.util.ListIterator;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.jface.wizard.WizardDialog;

public class AddPlayerAction extends Action {
   private ApplicationWindow window;
   public AddPlayerAction(ApplicationWindow window) {
      setText("Add Player...");
      this.window = window;
   }

   public void run() {
      if(isStarted()){
         MessageDialog.openError(
               window.getShell(), 
               "Error",
               "Can't add player!"
               + System.getProperty("line.separator")
               + "The game has already started!");
         return;
      } else if(!canAdd()){
         MessageDialog.openError(
               window.getShell(), 
               "Error",
               "Can't add player!"
               + System.getProperty("line.separator")
               + "4 is the maximum number of players!"
               + System.getProperty("line.separator")
               + "You can start the game now!");
         return;
      } else {
         // Instantiates and initializes the wizard
         AddPlayerWizard wizard = new AddPlayerWizard();

         // Instantiates the wizard container with the wizard and opens it
         WizardDialog dialog = new WizardDialog(window.getShell(), wizard);
         dialog.create();
         dialog.open();

         ((ApplicationStart)window).updateWaitingList();
      } 
   }
   
   boolean isStarted(){
      GameManager gm = GManager.instance().getGameManager();
      return gm.isGameStarted();
   }
   
   boolean canAdd(){
      GameManager gm = GManager.instance().getGameManager();
      ListIterator iter = gm.getBoard().iteratorOfSeatPlace();
      int playerCount = 0;
      while(iter.hasNext()){
         SeatPlace seat = (SeatPlace)iter.next();
         if(seat.getPlayer() != null){
            playerCount++;
         }
      }
      return playerCount < 4;
   }
}
